package com.cy.train.gateway.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Date: 2024/2/27 10:08
 * @Author: cyzhang
 */
public class JwtUtil {
    private static final Logger LOG = LoggerFactory.getLogger(JwtUtil.class);
    private static final String key = "cy12306";

    public static String createToken(Map<String, Object> values) {
        Map<String, Object> payload = new HashMap<>();
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, 24);
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //内容
        for(Map.Entry<String, Object> entry : values.entrySet()) {
            payload.put(entry.getKey(), entry.getValue());
        }
        String token = JWTUtil.createToken(payload, key.getBytes());
        LOG.info("生成的JWT token: {}", token);
        return token;
    }

    public static boolean validate(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
            boolean validate = jwt.validate(0);
            LOG.info("JWT token校验结果: {}", validate);
            return validate;
        } catch (Exception e) {
            LOG.info("JWT token校验异常", e);
            return false;
        }
    }

    public static JSONObject getJSONObject(String token) {
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        JSONObject payload = jwt.getPayloads();
        payload.remove(JWTPayload.ISSUED_AT);
        payload.remove(JWTPayload.EXPIRES_AT);
        payload.remove(JWTPayload.NOT_BEFORE);
        LOG.info("token解析结果: {}", payload);
        return payload;
    }
}
